package com.example.nacos.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class HelloController {

//    private final RandomServiceInstanceChooser randomChooser;

    private final DiscoveryClient discoveryClient;

    private final RestTemplate restTemplate;

    private final String serviceName;

    @Autowired
    public HelloController(DiscoveryClient discoveryClient, RestTemplate restTemplate) {
//        this.randomChooser = new RandomServiceInstanceChooser();
        this.discoveryClient = discoveryClient;
        this.restTemplate = restTemplate;
        this.serviceName = "nacosprovider";
    }

//    @GetMapping("/customChooser")
//    public String customChooser(){
//        ServiceInstance serviceInstance =
//    }

    @GetMapping("/info")
    public String info(){
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceName);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("All services: ")
                .append(discoveryClient.getServices())
                .append("<br/>");
        stringBuilder.append("nacosprovider instance list: <br/>");
        serviceInstances.forEach(
                serviceInstance -> {
                    stringBuilder.append("[ serviceId: ")
                            .append(serviceInstance.getServiceId())
                            .append(", host: ")
                            .append(serviceInstance.getHost())
                            .append(", port: ")
                            .append(serviceInstance.getPort())
                            .append(", instanceId: ")
                            .append(serviceInstance.getInstanceId())
                            .append(" ]");
                }
        );
        return stringBuilder.toString();
    }

    @GetMapping("/hello")
    public String hello(){
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceName);
        ServiceInstance serviceInstance = serviceInstances.stream().findAny().orElseThrow(
                ()-> new IllegalStateException("no " + serviceName + " instance available")
        );
        return restTemplate.getForObject(
                "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort()
                + "/echo?name=nacos",
                String.class
        );

    }
}
